package com.example.download

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.download.databinding.ActivityDownloadBinding

class DownloadActivity : AppCompatActivity() {
    val tag = "Download"
    private lateinit var binding: ActivityDownloadBinding
    private val progressBar : ProgressBar by lazy {
        findViewById(R.id.progressBar)
    }
    private val progressText : TextView by lazy {
        findViewById(R.id.progressText)
    }
    private val statusText : TextView by lazy {
        findViewById(R.id.statusText)
    }
    private var isDownloading = false
    private var downloadThread: Thread? = null

    companion object{
        private const val MSG_UPDATE_PROGRESS = 1
        private const val MSG_DOWNLOAD_COMPLETE = 2
        private const val MSG_DOWNLOAD_CANCELED = 3
        private const val MSG_DOWNLOAD_ERROR = 4
    }

    private val handler = object : Handler(Looper.getMainLooper()){//handler的作用：在主线程和子线程中传递消息，这句代码就是跳回主线程
        override fun handleMessage(msg: Message) {
//            super.handleMessage(msg)
        when(msg.what){
            MSG_UPDATE_PROGRESS -> {
                val progress = msg.arg1
                progressBar.progress = progress
                progressText.text = "$progress%"
            }
            MSG_DOWNLOAD_COMPLETE -> {
//                statusText.text = "下载完成!"
                statusText.setText("下载已完成")
                resetDownloadState()
            }
            MSG_DOWNLOAD_CANCELED -> {
                statusText.text = "下载已取消"
                resetDownloadState()
            }
            MSG_DOWNLOAD_ERROR -> {
                statusText.text = "下载出错: ${msg.obj}"
                resetDownloadState()
            }

        }
        }
    }



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDownloadBinding.inflate(layoutInflater)
        setContentView(binding.root)
        with(binding){
            startButton.setOnClickListener{
                startDownload()
                Log.d(tag,"${progressText.text}+${progressBar.progress}")
            }
            cancelButton.setOnClickListener{
                cancelDownload()
                Log.d(tag,"${progressText.text}+${progressBar.progress}")
            }
        }
        progressBar.progress = 0
        progressText.text = "0%"
        statusText.text = "准备就绪"
    }

    private inner class DownloadRunnable : Runnable{
        override fun run() {
            try {
                for (i in 1..100){
                    if (!isDownloading || Thread.currentThread().isInterrupted) {
                        handler.sendEmptyMessage(MSG_DOWNLOAD_CANCELED)
                        return
                    }
                    // 模拟下载耗时
                    Thread.sleep(100)

                    // 发送进度更新消息
                    handler.sendMessage(Message.obtain().apply {
                        what = MSG_UPDATE_PROGRESS
                        arg1 = i
                    })
                }
                handler.sendEmptyMessage(MSG_DOWNLOAD_COMPLETE)
            }catch (e : InterruptedException){
                handler.sendMessage(Message.obtain().apply {
                    what = MSG_DOWNLOAD_ERROR
                    obj = e.message
                })
            }
        }
    }

    private fun startDownload(){
        if (isDownloading) return
        isDownloading = true
        progressBar.progress = 0
        progressText.text = "0%"
        statusText.text = "下载中"
        downloadThread = Thread(DownloadRunnable()).apply {
            start()
        }
    }
    private fun cancelDownload(){
        if (!isDownloading) return
        isDownloading = false
        downloadThread?.interrupt()
        handler.sendEmptyMessage(MSG_DOWNLOAD_CANCELED)
    }
    private fun resetDownloadState(){
        isDownloading = false
        downloadThread = null
    }
    override fun onDestroy() {
        super.onDestroy()
        // 取消下载并清理资源
        cancelDownload()
        handler.removeCallbacksAndMessages(null)
    }
}